<template>
	<view class="container">
		<view style="padding: 10px;background-color: #fff;">
			<u-cell-group :customStyle="{'background-color': '#fff'}">
				<u-cell size="large" title="项目名称" :value="proDetail.title"></u-cell>
				<u-cell size="large" title="业主名称" :value="proDetail.name"></u-cell>
				<u-cell size="large" title="业主电话" :value="proDetail.tel"></u-cell>
				<u-cell size="large" title="小区名称" :value="proDetail.village"></u-cell>
				<u-cell size="large" title="详细地址" :value="proDetail.address"></u-cell>
				<u-cell size="large" title="项目开始时间" :value="proDetail.startdate"></u-cell>
				<u-cell size="large" title="项目结束时间" :value="proDetail.expectenddate"></u-cell>
				<block v-if="departmentid == 4">
					<u-cell size="large" title="设计开始时间" :value="proDetail.sheji_startdate"></u-cell>
					<u-cell size="large" title="设计结束时间" :value="proDetail.sheji_enddate"></u-cell>
				</block>
				<u-cell size="large" title="监理" :value="proDetail.jianli_name"></u-cell>
				<u-cell v-if="departmentid == 5" size="large" title="添加跟踪记录" isLink @click="showRecord = true"></u-cell>
			</u-cell-group>
			
			<!-- 添加收款凭据 -->
			<u-button
				@click="showReceipt = true" 
				color="#5f6199"
				customStyle="margin: 10px 0">
				添 加 收 款 凭 据
			</u-button>
			<view class="u-page">
					<u-list
						height="100%"
					>
						<u-list-item
							v-for="(item, index) in proJectMoneyList"
							:key="index"
						>
							<u-cell
								:title="`${item.realname}; 金额：${item.amount}`"
								:value="item.reciverdate"
								:label="`备注：${item.remark}`"
								@click="handleViewPro(item)"
							>
								<u-avatar
									slot="icon"
									shape="square"
									size="35"
									:src="item.pics.length?item.pics[0]['picurl']:''"
									customStyle="margin: -3px 5px -3px 0"
								></u-avatar>
							</u-cell>
						</u-list-item>
					</u-list>
				</view>
			<!-- 日历 -->
			<block v-if="departmentid != 5">
				<kjCalendar 
					:startDate="startDate" 
					:endDate="endDate" 
					:workLogList="workLogList" 
					@handleSelectDay="handleSelectDay"
					>
				</kjCalendar>
			</block>
			
			<!-- 进度条 -->
			<view>
				<view class="progress">
					<view>项目进度：</view>
					<u-line-progress :percentage="proDetail.percent" activeColor="#5f6199" height="18"></u-line-progress>
				</view>
				<view class="day_box">
					<view class="tj_box">
						<view class="icon_tj" style="background-color: #232773;"></view>
						<view>总天数：{{proDetail.totaldays}}天</view>
					</view>
					<view class="tj_box">
						<view class="icon_tj" style="background-color: #c1c2d8;"></view>
						<view>异常天数：{{proDetail.yichangdays}}天</view>
					</view>
					<view class="tj_box">
						<view class="icon_tj" style="background-color: #5f6199;"></view>
						<view>开工天数：{{proDetail.workdays}}天</view>
					</view>
					<view class="tj_box">
						<view class="icon_tj" style="background-color: #ea7f87;"></view>
						<view>未开工天数：{{proDetail.noworkdays}}天</view>
					</view>
				</view>
			</view>
			
			<!-- 开工弹窗 -->
			<u-modal 
				:show="showWorklog" 
				:title="workTitle" 
				@confirm="confirmWorklog" 
				ref="worklogModal"
				:closeOnClickOverlay="true"
				@close="closeWorklog"
				:showConfirmButton="!isWorkDetail"
				>
				<view class="slot-content" style="width:260px">
					<u-form :model="workData" :rules="rules" ref="formWork" :labelStyle="{'margin-bottom':'10px'}">
						<u-form-item v-if="departmentid != 4" label="是否开工"  labelWidth="70" borderBottom prop="iswork">
							<u-switch v-model="workData.iswork" :disabled="isWorkDetail"></u-switch>
						</u-form-item>
						<u-form-item label="图片" labelWidth="70" borderBottom prop="title">
							<u-upload
								v-if="!isWorkDetail"
								:fileList="fileList1"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="9"
							></u-upload>
							<block v-if="isWorkDetail">
								<u--image 
									v-for="(item,index) in fileList1"
									:key="index"
									:src="item" 
									width="80px" 
									height="80px" 
									@click="showBigImage(fileList1,index)"></u--image>
							</block>
						</u-form-item>
						<u-form-item 
							label="备注" 
							labelPosition="top" 
							borderBottom prop="remark">
							<u--textarea 
								v-model="workData.remark" 
								placeholder="备注" 
								:disabled="isWorkDetail" />
						</u-form-item>
					</u-form>
				</view>
			</u-modal>
			
			<!-- 添加跟踪记录 -->
			<u-modal
				:show="showRecord"
				title="添加跟踪记录" 
				@confirm="confirmRecord" 
				ref="recordModal"
				:closeOnClickOverlay="true"
				@close="closeRecord">
				<view class="slot-content" style="width:260px">
					<u-form 
						:model="recordData" 
						:rules="rules2" 
						ref="formRecord" 
						:labelStyle="{'margin-bottom':'10px'}">
						<u-form-item
							label="选择时间" 
							labelWidth="70"
							labelPosition="top"
							borderBottom 
							prop="workdate" 
							required
							>
							<u-datetime-picker
								:show="startDateShow"
								mode="date"
								v-model="defDate1"
								@confirm="confirmStartDate"
								@cancel="startDateShow = false"
							></u-datetime-picker>
							<u--input 
								@tap="startDateShow = true" 
								v-model="recordData.workdate" 
								border="none" 
								readonly
								placeholder="请选择时间" />
						</u-form-item>
						<u-form-item 
							label="备注" 
							labelPosition="top" 
							borderBottom prop="remark">
							<u--textarea 
								v-model="recordData.remark" 
								placeholder="备注"  />
						</u-form-item>
					</u-form>
				</view>
			</u-modal>
			
			<!-- 收款凭据弹窗 -->
			<u-modal 
				:show="showReceipt" 
				:title="proJectDetail?'收款明细':'添加收款记录'" 
				@confirm="confirmReceipt" 
				ref="receiptModal"
				:closeOnClickOverlay="true"
				@close="closeReceipt"
				@cancel="closeReceipt"
				:showConfirmButton="!proJectDetail"
				:showCancelButton="proJectDetail"
				>
				<view class="slot-content" style="width:260px">
					<u-form :model="receiptData" :rules="rules3" ref="formReceipt" :labelStyle="{'margin-bottom':'10px'}">
						<u-form-item
							label="金额" 
							labelWidth="70"
							borderBottom prop="amount">
							<u--input 
								type="number"
								:readonly="proJectDetail"
								v-model="receiptData.amount" 
								@input="receiptData.amount = receiptData.amount.replace(/[^\d]/g, '')"
								required
								placeholder="金额"/>
						</u-form-item>
						<u-form-item label="图片" labelWidth="70" borderBottom prop="title">
							<u-upload
								v-if="!proJectDetail"
								:fileList="fileList2"
								@afterRead="afterReceipt"
								@delete="deleteReceipt"
								name="2"
								multiple
								:maxCount="9"
							></u-upload>
							<block v-if="proJectDetail">
								<u--image 
									v-for="(item,index) in fileList2"
									:key="index"
									:src="item" 
									width="80px" 
									height="80px" 
									@click="showBigImage(fileList2,index)"></u--image>
							</block>
						</u-form-item>
						<u-form-item
							label="选择时间" 
							labelWidth="70"
							labelPosition="top"
							borderBottom 
							prop="reciverdate" 
							required
							>
							<u-datetime-picker
								:show="reciverdateShow"
								mode="date"
								v-model="defDate2"
								@confirm="confirmReciverdateShow"
								@cancel="reciverdateShow = false"
							></u-datetime-picker>
							<u--input 
								@tap="reciverdateShow = !proJectDetail" 
								v-model="receiptData.reciverdate" 
								border="none" 
								readonly
								placeholder="请选择时间" />
						</u-form-item>
						<u-form-item 
							label="备注" 
							labelPosition="top" 
							borderBottom prop="remark">
							<u--textarea 
								v-model="receiptData.remark"
								 :disabled="proJectDetail"
								placeholder="备注"/>
						</u-form-item>
					</u-form>
				</view>
			</u-modal>
			
			<u-button
				v-if="(departmentid==3&&[2,3].includes(status))||(departmentid==4&&status==1)||(departmentid==5&&status==0)"
				:loading="loading"
				@click="handleProliu" 
				color="#5f6199"
				customStyle="margin: 10px 0">
				{{btnText}}
			</u-button>
			
			<u-button
				v-if="iscanadd"
				@click="handleAddProject" 
				color="#232773"
				customStyle="margin: 10px 0">
				编 辑 项 目
			</u-button>
			<project-sub ref="projectSubRef" @proSubHandle="proSubHandle"></project-sub>
		</view>
	</view>
</template>

<script>
	import { getPage } from '../../utils/config';
	import { imageCdn } from '../../utils/api';
	import { prosimify, $toast, http, storage } from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import api from '../../utils/api';
	import uploadImage from '@/utils/aliyunoss/uploadAliyun.js'
	import kjCalendar from '@/components/calendar/index.vue';
	import projectSub from './projectSub.vue';
	const app = getApp();
	export default {
		components:{ "kj-calendar": kjCalendar,'project-sub':projectSub},
		data() {
			return {
				id:0,
				userid: 0,
				departmentid:null,
				showCal:false,
				mode:'range',
				defaultDate:['2024-08-07','2024-08-16'],
				minDate: new Date(new Date().setDate(new Date().getDate() - 30)),
				maxDate: new Date(new Date().setDate(new Date().getDate() + 60)),
				proDetail:{
					startdate:'',
					expectenddate:'',
				},
				startDate:'',
				endDate:'',
				workLogList:[],
				showWorklog:false,
				workTitle:'添加项目开工记录',
				isWorkDetail:false,
				workData:{
					iswork:false,
					remark:'',
					pics:[]
				},
				rules: {
					remark: {
						type: 'string',
						required: true,
						message: '请填写备注',
						trigger: ['blur', 'change']
					},
				},
				rules2: {
					workdate: {
						required: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					},
				},
				rules3: {
					amount: {
						type:'number',
						required: true,
						message: '请填写金额',
						trigger: ['blur', 'change']
					},
					reciverdate: {
						required: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					},
				},
				fileList1: [],
				fileList2:[],
				showRecord:false,
				startDateShow:false,
				recordData:{
					workdate:'',
					remark:''
				},
				defDate1:Number(new Date()),
				defDate2:Number(new Date()),
				showReceipt:false,
				reciverdateShow:false,
				receiptData:{
					remark:'',
					reciverdate:'',
					pics:[],
					amount:undefined
				},
				proJectMoneyList:[],
				proJectDetail:false,
				status:undefined,
				btnText:'',
				iscanadd:false,
				loading:false
			}
		},
		onLoad(options){
			if (JSON.stringify(options) !== '{}'){
				let { id } = options
				this.id = id
				storage.get('userInfo').then(res=>{
					console.log('登录信息--userInfo------->',res)
					this.userid = res.data.userid;
					// departmentid 1-管理 2-财务 3-监理 4-设计 5-业务
					this.departmentid = res.data.departmentid;
					this.companyid = res.data.companyid;
					this.iscanadd = res.data.iscanadd;
					this.getProjectDetail()
					this.getworklogs()
					this.getprojectmoney()
				})
			}
		},
		onReady(){
			this.$refs.formWork.setRules(this.rules);
			this.$refs.formRecord.setRules(this.rules2);
			this.$refs.formReceipt.setRules(this.rules3);
		},
		methods: {
			
			/**
			 * 获取项目详情
			 * getprojectinfo
			 * id 项目ID
			 * userid  当前登录用户ID
			 */
			getProjectDetail(){
				console.log('userid·······',this.userid)
				let data = {
					action: 'getprojectinfo',
					id: this.id,
					userid: this.userid
				}
				http.post(api.default, { data }).then(res=>{
					this.proDetail = res.data.data;
					this.status = this.proDetail.status;
					let {province,city,district,} = res.data.data.zonedata || {}
					let startDate = this.departmentid != 4? res.data.data.startdate : res.data.data.sheji_startdate
					let endDate = this.departmentid != 4? res.data.data.expectenddate : res.data.data.sheji_enddate
					this.startDate = startDate.slice(0,10).split('-').join('/')
					this.endDate = endDate.slice(0,10).split('-').join('/')
					let cityName = province.name+'-'+city.name+'-'+district.name
					if(this.departmentid == 5){
						this.btnText = '成 交 并 转 设 计'
					}else if(this.departmentid == 4){
						this.btnText = '设 计 完 成'
					}else if(this.departmentid == 3){
						this.status == 2?this.btnText ='项 目 验 收':this.btnText ='项 目 完 工'
					}
					this.$set(this.proDetail,'cityName',cityName)
				})
			},
			
			/**
		    * 获取项目开工记录
		    * getworklogs
		    * projectid 项目ID
		    * userid  当前登录用户ID
		    */
			async getworklogs(){
				let data = {
					action: 'getworklogs',
					projectid: this.id,
					userid: this.userid,
					departmentid:this.departmentid
				}
				const res = await http.post(api.default, { data })
				console.log('获取项目开工记录~~~~~',res.data.data)
				this.workLogList = res.data.data
			},
			
			/**
			* 获取项目收款明细
			* getprojectmoney
			* projectid 项目ID
			* userid  当前登录用户id
			*/
			async getprojectmoney(){
				let data = {
					action: 'getprojectmoney',
					projectid: this.id,
					userid: this.userid
				}
				const res = await http.post(api.default, { data })
				let prolist = res.data.data
				prolist.forEach(item=>{
					item.pics = JSON.parse(item.pics) || []
					item.reciverdate = item.reciverdate.slice(0,10)
				})
				console.log('获取项目收款明细~~~~~prolist',prolist)
				this.proJectMoneyList = prolist
			},
			
			// 选择日期
			handleSelectDay(item){
				console.log('选择日期逻辑~~~~',item)
				if(item.workdate){
					// 详情
					this.workTitle = '日志信息';
					this.isWorkDetail = true;
					let parms ={
						action:'getloginfo',
						userid:this.userid,
						date:item.workdate
					}
					http.post(api.default, { data: parms }).then(res=>{
						let { data } = res.data;
						let pics = data.pics && JSON.parse(data.pics);
						this.workData ={
							iswork:data.iswork || false,
							remark:data.remark || '',
							pics:pics||[]
						}
						console.log('dayin~~~~~~',pics)
						this.fileList1 = pics.map(m=> m.picurl)
					})
				}else{
					this.workData ={
						iswork:false,
						remark:'',
						pics:[]
					}
					this.fileList1 = []
					this.departmentid == 4?this.workTitle = '添加设计工作记录':this.workTitle = '添加项目开工记录';
					this.isWorkDetail = false;
					this.workdate = item.date.split('/').join('-');
				}
				this.showWorklog = true
			},
			
			// 关闭弹窗
			closeWorklog(){
				this.workData ={
					iswork:false,
					remark:'',
					pics:[]
				}
				this.fileList1 = []
				this.showWorklog = false;
				this.$refs.formWork.clearValidate()
			},
			
			// 确认添加开工
			confirmWorklog() {
				this.$refs.formWork.validate().then(()=>{
					
					let { iswork,remark,pics } = this.workData
					
					let parms = {
						action: 'addworklog',
						projectid:this.id,
						userid:this.userid,
						departmentid:this.departmentid,
						iswork,
						remark,
						pics:JSON.stringify(pics),
						workdate:this.workdate
					}
					// 设计-是否开工默认传true
					if(this.departmentid == 4) parms.iswork = true
					console.log('传值···············',parms)
					
					http.post(api.default, { data: parms }).then(res=>{
						const { data } = res.data;
						if (res.data.code == 0) {
						    $toast(`成功`, {
						        icon: 'success',
						        times: 300
						    }).then(() => {
								this.getProjectDetail()
								this.getworklogs()
								this.showWorklog = false;
						    });
						} else {
						    $toast(res.errmsg);
							this.showWorklog = false;
						}
					})
				}).catch(errors => {
					uni.$u.toast('请填写完整的信息')
				})
			},
			
			// 开工记录-删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.workData.pics.splice(event.index, 1)
			},
			
			// 开工记录-新增图片
			async afterRead(event) {
				let that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
					})
				})
				// let pics = { picurl:'' }
				let pics = []
				console.log('薪增图片---lists',lists)
				console.log('薪增图片this.fileList1',this.fileList1)
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i].url,'lists[i].url')
					uploadImage({
						filePath: lists[i].url,
						dir: "worklog",
						success(res) {
						   var img_url = api.imageCdn + res
						   console.log('img_url--------',img_url)
						   pics.picurl = img_url
						   pics.push({picurl:img_url})
						   that.workData.pics =[...new Set([...that.workData.pics,...pics])]
						},
						fail(res) {
						  $toast(`图片上传失败${res}`);
						}
					});
				}
			},
			
			// 凭据-新增图片
			async afterReceipt(event) {
				let that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
					})
				})
				// let pics = { picurl:'' }
				let pics = []
				console.log('薪增图片---lists',lists)
				console.log('薪增图片this.fileList2',this.fileList2)
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i].url,'lists[i].url')
					uploadImage({
						filePath: lists[i].url,
						dir: "receipt",
						success(res) {
						   var img_url = api.imageCdn + res
						   console.log('img_url--------',img_url)
						   pics.picurl = img_url
						   pics.push({picurl:img_url})
						   that.receiptData.pics =[...new Set([...that.receiptData.pics,...pics])]
						},
						fail(res) {
						  $toast(`图片上传失败${res}`);
						}
					});
				}
			},
			// 凭据-删除图片
			deleteReceipt(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.receiptData.pics.splice(event.index, 1)
			},
			
			showBigImage(fileList1,index) {
				uni.previewImage({
				  urls: fileList1,
				  current:index
				});
			},
			
			// 确认时间
			confirmStartDate(e){
				var dateS = this.$com.formatTimestamp(e.value,'Y-m-d')
				console.log('确认开始时间---------',dateS)
				this.recordData.workdate = dateS
				this.startDateShow = false;
			},
			
			
			// 确认添加跟踪记录
			confirmRecord(){
				this.$refs.formRecord.validate().then(()=>{
					let { workdate,remark } = this.recordData
					let parms = {
						action:'addworklog',
						workdate,
						remark,
						projectid:this.id,
						userid:this.userid,
						departmentid:this.departmentid,
						iswork:true
					}
					console.log('传值···············',parms)
					
					http.post(api.default, { data: parms }).then(res=>{
						const { data } = res.data;
						if (res.data.code == 0) {
						    $toast(`成功`, {
						        icon: 'success',
						        times: 300
						    }).then(() => {
								this.getProjectDetail()
								this.showRecord = false;
						    });
						} else {
						    $toast(res.errmsg);
							this.showRecord = false;
						}
					})
				}).catch(errors => {
					uni.$u.toast('请填写完整的信息')
				})
			},
			
			closeRecord(){
				this.recordData ={
					workdate:'',
					remark:''
				}
				this.showRecord = false;
				this.$refs.formRecord.clearValidate()
			},
			
			// 收据-确认时间
			confirmReciverdateShow(e){
				var dateS = this.$com.formatTimestamp(e.value,'Y-m-d')
				console.log('确认开始时间---------',dateS)
				this.receiptData.reciverdate = dateS
				this.reciverdateShow = false;
			},
			
			// 提交收款凭据
			confirmReceipt(){
				this.$refs.formReceipt.validate().then(()=>{
					let { remark,pics,amount,reciverdate } = this.receiptData
					
					let parms = {
						action: 'addprojectmoney',
						projectid:this.id,
						userid:this.userid,
						amount,
						reciverdate,
						remark,
						pics:JSON.stringify(pics)
					}
					// 设计-是否开工默认传true
					console.log('传值···············',parms)
					
					http.post(api.default, { data: parms }).then(res=>{
						const { data } = res.data;
						if (res.data.code == 0) {
						    $toast(`成功`, {
						        icon: 'success',
						        times: 300
						    }).then(() => {
								this.getprojectmoney()
								this.showReceipt = false;
						    });
						} else {
						    $toast(res.errmsg);
							this.showReceipt = false;
						}
					}).catch(err=>{
						console.log('errrrrrrrr',err)
					})
				}).catch(errors => {
					uni.$u.toast('请填写完整的信息')
				})
			},
			
			// 取消收款凭据
			closeReceipt(){
				this.showReceipt = false;
				this.proJectDetail = false;
				this.receiptData = {
					remark:'',
					reciverdate:'',
					pics:[],
					amount:undefined
				}
				this.fileList2 = []
				this.$refs.formReceipt.clearValidate()
			},
			
			// 查看收款记录
			handleViewPro(item){
				console.log('查看收款记录~~~~~~~',item)
				this.proJectDetail = true;
				this.showReceipt = true;
				this.receiptData = {
					remark:item.remark,
					reciverdate:item.reciverdate,
					pics:item.pics,
					amount:item.amount
				}
				this.fileList2 = item.pics.map(m=> m.picurl);
			},
			
			// 设计和业务流转
			async handleProliu(){
				if(this.departmentid==4||this.departmentid==5){
					// 业务用户和设计用户需要选择设计师和监理
					this.$refs.projectSubRef.show({
						userid:this.userid,
						companyid: this.companyid,
						projectid:this.id,
						departmentid:this.departmentid})
				}else{
					let action = this.status == 2?'toyanshou':'projectcomplete';
					let data = {
						action,
						userid: this.userid,
						projectid: this.id
					}
					this.loading = true
					const res = await http.post(api.default, { data })
					if (res.data.code == 0) {
					    $toast(`成功`, {
					        icon: 'success',
					        times: 300
					    }).then(() => {
							this.getProjectDetail()
					    });
					} else {
					    $toast(res.errmsg);
					}
					this.loading = false
				}
			},
			
			// 监听流转事件
			proSubHandle(){
				console.log('监听proSubHandle~~~')
				this.getProjectDetail()
			},
			
			// 跳转编辑项目
			handleAddProject(){
				let province_id = this.proDetail.zonedata.province.id
				let city_id = this.proDetail.zonedata.city.id
				let district_id = this.proDetail.zonedata.district.id
				wxApi.navigateTo(
					getPage.editProject,
					Object.assign({},
					{ id:this.id,province_id,city_id,district_id},this.proDetail)
				);
			},
		}
	}
</script>

<style scoped lang="scss">
	.progress{
		display: flex;
		align-items: center;
		margin-top: 15px;
		padding: 0 10px;
	}
	.day_box{
		display: flex;
		flex-wrap: wrap;
	}
	.tj_box{
		display: flex;
		padding: 0 5px;
		width: 45%;
		margin-top: 10px;
	}
	.icon_tj{
		width: 30px;
		height: 20px;
		margin-right: 5px;
		border-radius: 10px;
		background-color: aqua;
	}
</style>
